package zgame.bussiness;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import zgame.bean.Table;
import zgame.bean.User;
import zgame.socket.DataPackage;

public class GameBaCayBussiness extends GameComponent {
  private static final Logger log = Logger.getLogger(GameBaCayBussiness.class);
  
  private static final int READY_IN_GAME_REQUEST = 3001;
  
  private static final int START_TO_PLAY_RESPONSE = 4001;
  
  private List<User> userReadyList;

  public GameBaCayBussiness(Table table) {
    super(table);
  }

  @Override
  public void init() {
    userReadyList = new ArrayList<User>();
  }

  @Override
  protected void onActionPerform(User user, DataPackage inputDataPackage) {
    int header = inputDataPackage.getHeader();
    switch (header) {
    case READY_IN_GAME_REQUEST:
      long timeReady = inputDataPackage.nextLong();
      log.info("Client " + user.getUsername() + " ready in " + timeReady);
      if (!userReadyList.contains(user)) {
        userReadyList.add(user);
      }
      
      if (userReadyList.size() == table.getConcurrentUser()) {
        DataPackage dataPackage = createGamePackage(START_TO_PLAY_RESPONSE);
        dataPackage.putString("Let's start game right now");
        for (User user1 : table.getUsers()) {
          user1.server.write(dataPackage);
        }
      }
      break;
    }
  }

  @Override
  public void onUserLeaveTable(User user) {
  }
  
  @Override
  public void detroy() {
  }
}
